#version 330 core
layout (location = 0) out vec4 FragColor;
layout (location = 1) out vec4 FragColorToBlur;
layout (location = 2) out vec4 FragColorDepth;

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
};

in vec2 TexCoords;

uniform Material material;

struct Light {
    vec3 position;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

uniform Light light;

in vec3 Normal;
in vec3 FragPos;

uniform vec3 viewPos;

in float Depth;

void main()
{
    // 环境光
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));

    // 漫反射
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(light.position - FragPos);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = light.diffuse * (diff * vec3(texture(material.diffuse, TexCoords)));

    // 镜面光
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * (spec * vec3(texture(material.specular, TexCoords)));

    vec3 result = ambient + diffuse + specular;
    FragColor = vec4(result, 1.0);


    FragColorToBlur = FragColor;
    float blur = 0;

    float near_distance = 1.0; // 近平面的模糊衰减范围
    float far_distance = 1.0; // 远平面的模糊衰减范围
 
    float near_plane = -3.0; // 近平面
    float far_plane = -6.0; // 远平面
 
    // 根据深度计算模糊因子
    if(Depth <= near_plane && Depth >= far_plane)
    {
        blur = 0;
    }
    else if(Depth > near_plane)
    {
        blur = clamp(Depth, near_plane, near_plane + near_distance);
        blur = (blur - near_plane) / near_distance;
    }
    else if(Depth < far_plane)
    {
        blur = clamp(Depth, far_plane - far_distance, far_plane);
        blur = (far_plane - blur) / far_distance;
    }
    FragColorDepth = vec4(blur, blur, blur, 1);
    // FragColorDepth = vec4(1.0, 1.0, 1.0, 1.0);
}
